<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>拖动</title>
    <style>
      #box {
        width: 150px;
        height: 150px;
        position: absolute;
        top: 0;
        left: 0;

        background-color: #000000;
      }
    </style>
  </head>
  <body>
    <div id="box"></div>
  </body>
  <script>
    var div = document.getElementById("box");
    div.onmousedown = function (ev) {
      var dX = ev.offsetX;
      var dY = ev.offsetY;
      window.onmousemove = function (e) {
        var x = e.clientX - dX;
        var y = e.clientY - dY;
        div.style.top = y + "px";
        div.style.left = x + "px";
      };
    };
    div.onmouseup = function () {
      window.onmousemove = null;
    };
  </script>
</html>
